<?php
	require "assets/db.php";
	$user = 'u1655009_default';
	$pass = 'kq6pI91sjLgYE49F';
	$db = new PDO('mysql:host=localhost;dbname=u1655009_default', $user, $pass);
	
	
	if ( isset($_GET['id']) ) {
	$query = "SELECT * FROM tovars WHERE id=" . $_GET['id'];

	$req = mysqli_query($connection, $query);
	$current_course = mysqli_fetch_assoc($req);
	// var_dump($current_course);

	if (empty($current_course)) {
		header("Location: 404.php");
	}
}


$date_file = date("dmYGiv");

$avatar = $_FILES['foto']['name'];
$avatar_user = addDateToFileName($avatar);

$id_polz = $current_course['id'];

function addDateToFileName($file_name){
        $name = substr($file_name, 0, strrpos($file_name, '.'));  
        $extension = substr($file_name, strrpos($file_name, '.'));

        $date_file = date('dmYGiv');

        return $date_file . $extension;
    }
	
	
function test_input($data) {
		$data = trim($data);
		$data = stripslashes($data);
		$data = htmlspecialchars($data);
		return $data;
	}
	
	
    $update_columns = array();
    if(trim($avatar_user) !== "")   { $update_columns[] = "photo_tovar = :photo_tovar"; }
	
	$sql = "UPDATE `tovars` SET " . implode(", ", $update_columns) . " WHERE `id` = $id_polz";
	
	$statement = $db->prepare($sql);
	
        if(trim($avatar_user) !== ""){
            $statement->bindParam(":photo_tovar", $avatar_user);
        }
	$statement->execute();
	

if(move_uploaded_file($_FILES['foto']['tmp_name'], 'adm/assets/images/' . $avatar_user)){
	header("Location: shop");
} else{
	header("Location: shop");
}
?>